// pages/search/search.js
import request from '../../utils/request'
let isSend = false
Page({
  data: {
    placeholderContent: '发现内容',
    searchContent: '',
    hotList: [],
    searchList: [],
    historyList: []
  },

  onLoad() {
    this.getSearchDefault()
    this.getHot()
    this.getHistory()
  },

  deleteSearchHistory() {
    this.setData({
      historyList: []
    })

  },

  async getSearchDefault() {
    let res = await request('search/default')
    if (res.code === 200) {
      this.setData({
        placeholderContent: res.data.showKeyword
      })
    }
  },

  async getHot() {
    let res = await request('search/hot/detail')
    if (res.code === 200) {
      this.setData({
        hotList: res.data
      })
    }
  },

  handleInputChange(e) {
    let searchContent = e.detail.value.trim()
    this.setData({
      searchContent
    })
    if (isSend) return;
    isSend = true;
    this.getSearchList()
    setTimeout(() => {
      isSend = false
    }, 1000)
  },
  async getSearchList() {

    if (!this.data.searchContent) {
      this.setData({
        searchList: []
      })
      return
    }
    let {
      searchContent,
      historyList
    } = this.data
    try {
      let res = await request('search', { limit: 10, keywords: searchContent })
      if (res.code === 200) {
        this.setData({ searchList: res.result.songs })
      }
      if (historyList.indexOf(searchContent) === -1) {
        historyList.unshift(searchContent)
      }
      this.setData({
        historyList
      })
      wx.setStorageSync('searchHistory', historyList)

    } catch (error) {
      console.log(error);
    }

  },
  getHistory() {
    let searchHistory = wx.getStorageSync('searchHistory')
    if (searchHistory) {
      this.setData({
        historyList
      })
    }
  },
  clearSearchContent() {
    this.setData({
      searchContent: '',
      searchList: []
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onShareTimeline() {}
})